<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Admin_Owners extends Admin_Controller {
	public function __construct()
	{
		parent::Admin_Controller();
		$this->load->helper('form');
		$this->lang->load('cirpho');
		$this->lang->load('owners');
		$this->load->model('cip_owners_m');
		$this->load->model('cip_servers_m');
		$this->template
			->append_metadata( css('cirpho.css', 'cirpho') )
			->set_partial('shortcuts', 'admin/partials/shortcuts');
		// Set the validation rules
		$this->load->library('form_validation');
		$this->validation_rules = array(
			array(
				'field' => 'name',
				'label' => lang('owner.title_label'),
				'rules' => 'trim|required|max_length[200]|callback__check_title'
			),
		);
		$this->form_validation->set_rules($this->validation_rules);
	}
	public function index()
	{
		$this->pyrocache->delete_all('modules_m');
		// Create pagination links
		$total_rows = $this->cip_owners_m->count_by('deleted', 0);
		$pagination = create_pagination('admin/cirpho/owners/index', $total_rows, NULL, 5);
		// Using this data, get the relevant results
		$owners = $this->cip_owners_m->where('deleted', 0)->order_by('id','desc')->limit($pagination['limit'])->get_all();
		$this->template
			->title($this->module_details['name'], lang('cirpho_category_list_title'))
			->set('owners', $owners)
			->set('pagination', $pagination)
			->build('admin/owners/index', $this->data);
	}
	/**
	 * Create method, creates a new category
	 * @access public
	 * @return void
	 */
	public function create()
	{
		
		// Validate the data
		if ($this->form_validation->run())
		{
			$id = $this->cip_owners_m->insert($_POST);
			$isSuccess = true;
			if($id){
				$servers = $this->cip_servers_m->get_all();
				
				if($servers && count($servers)){
					foreach ($servers as $server){
						
						$config['hostname'] = $server->domain_name;
						$config['username'] = $server->database_user;
						$config['password'] = $server->database_password;
						$config['database'] = $server->database_name;
						$config['dbdriver'] = "mysql";
						$config['dbprefix'] = "";
						$config['pconnect'] = FALSE;
						$config['db_debug'] = FALSE;
						$config['cache_on'] = FALSE;
						$config['cachedir'] = "";
						$config['char_set'] = "utf8";
						$config['dbcollat'] = "utf8_general_ci";
						$config['port'] 	= 3306;
						
						$this->client_db = $this->load->database($config, TRUE);
						
						$dataSet = array(
								'id' => $id,
								'name' => $_POST['name'],
						  		'slug'	=>url_title(strtolower(convert_accented_characters($_POST['name'])))  
						);
						
					    $this->client_db->insert('default_cip_owners', $dataSet);
					    
					    $e = $this->client_db->_error_message();
					    $aff = $this->client_db->affected_rows();
						
						if($aff < 1) {
							$isSuccess = false;
							//echo "Error";
							$this->cip_owners_m->delete($id);
							foreach ($servers as $server){
								$config['hostname'] = $server->domain_name;
								$config['username'] = $server->database_user;
								$config['password'] = $server->database_password;
								$config['database'] = $server->database_name;
								$config['dbdriver'] = "mysql";
								$config['dbprefix'] = "";
								$config['pconnect'] = FALSE;
								$config['db_debug'] = FALSE;
								$config['cache_on'] = FALSE;
								$config['cachedir'] = "";
								$config['char_set'] = "utf8";
								$config['dbcollat'] = "utf8_general_ci";
								$config['port'] 	= 3306;
								
								$this->client_db = $this->load->database($config, TRUE);

								$this->client_db->delete('default_cip_owners', array('id' => $id)); 
							}
							break;
						}
					}
				}else{
					$isSuccess = false;
				}
				
				$isSuccess ? $this->session->set_flashdata('success', sprintf( lang('cirpho_owner_add_success'), $this->input->post('name')) )
				: $this->session->set_flashdata(array('error'=> lang('cirpho_owner_add_error')));
			}
			redirect('admin/cirpho/owners');
		}
		
		// Loop through each validation rule
		foreach($this->validation_rules as $rule)
		{
			$owner->{$rule['field']} = set_value($rule['field']);
		}
		// Render the view	
		$this->data->owner =& $owner;	
		$this->template->title($this->module_details['name'], lang('cirpho_owner_create_title'))
						->build('admin/owners/form', $this->data);	
	}
	
	/**
	 * Edit method, edits an existing category
	 * @access public
	 * @param int id The ID of the category to edit 
	 * @return void
	 */
	public function edit($id = 0)
	{	
		// Get the category
		$owner = $this->cip_owners_m->get($id);
		
		// ID specified?
		$owner or redirect('admin/cirpho/owners/index');
		
		// Validate the results
		if ($this->form_validation->run())
		{		
			$updateResult = $this->cip_owners_m->update($id, $_POST);
			$isSuccess = true;
			if($updateResult){
				$servers = $this->cip_servers_m->get_all();
				
				if($servers && count($servers)){
					foreach ($servers as $server){
						
						$config['hostname'] = $server->domain_name;
						$config['username'] = $server->database_user;
						$config['password'] = $server->database_password;
						$config['database'] = $server->database_name;
						$config['dbdriver'] = "mysql";
						$config['dbprefix'] = "";
						$config['pconnect'] = FALSE;
						$config['db_debug'] = FALSE;
						$config['cache_on'] = FALSE;
						$config['cachedir'] = "";
						$config['char_set'] = "utf8";
						$config['dbcollat'] = "utf8_general_ci";
						$config['port'] 	= 3306;
						
						$this->client_db = $this->load->database($config, TRUE);
						
						$dataSet = array(
								'name' => $_POST['name'],
						  		'slug'	=>url_title(strtolower(convert_accented_characters($_POST['name'])))  
						);
						
						$this->client_db->where('id', $id);
						$this->client_db->update('default_cip_owners', $dataSet);
					    
					    $e = $this->client_db->_error_message();
					    $aff = $this->client_db->affected_rows();
						
						if($aff < 1) {
							$isSuccess = false;
							//echo "Error";
							//echo $e;
							
							$oldDataSet = array(
								'name' => $owner->name,
						  		'slug'	=>url_title(strtolower(convert_accented_characters($owner->name)))
							);

							$this->cip_owners_m->update($id, $oldDataSet);
						
							foreach ($servers as $server){
								$config['hostname'] = $server->domain_name;
								$config['username'] = $server->database_user;
								$config['password'] = $server->database_password;
								$config['database'] = $server->database_name;
								$config['dbdriver'] = "mysql";
								$config['dbprefix'] = "";
								$config['pconnect'] = FALSE;
								$config['db_debug'] = FALSE;
								$config['cache_on'] = FALSE;
								$config['cachedir'] = "";
								$config['char_set'] = "utf8";
								$config['dbcollat'] = "utf8_general_ci";
								$config['port'] 	= 3306;
								
								$this->client_db = $this->load->database($config, TRUE);

								$this->client_db->where('id', $id);
								$this->client_db->update('default_cip_owners', $oldDataSet); 
							}
							break;
						}
					}
				}
			}else{
				$isSuccess = false;
			}
			$isSuccess ? $this->session->set_flashdata('success', sprintf( lang('cirpho_owner_edit_success'), $this->input->post('name')) )
				: $this->session->set_flashdata(array('error'=> lang('cirpho_owner_edit_error')));	
				
			redirect('admin/cirpho/owners/index');
		}
		
		// Loop through each rule
		foreach($this->validation_rules as $rule)
		{
			if($this->input->post($rule['field']) !== FALSE)
			{
				$owner->{$rule['field']} = $this->input->post($rule['field']);
			}
		}

		// Render the view
		$this->data->owner =& $owner;
		$this->template->title($this->module_details['name'], sprintf(lang('cirpho_owner_edit_title'), $category->name))
						->build('admin/owners/form', $this->data); 
	}	

	/**
	 * Delete method, deletes an existing category (obvious isn't it?)
	 * @access public
	 * @param int id The ID of the category to edit 
	 * @return void
	 */
	public function delete($id = 0)
	{	
		$id_array = (!empty($id)) ? array($id) : $this->input->post('action_to');
		
		// Delete multiple
		if(!empty($id_array))
		{
			$deleted = 0;
			$to_delete = 0;
			$isSuccess = true;
			foreach ($id_array as $id) 
			{
				if(!$isSuccess){
					break;
				}
				$owner = $this->cip_owners_m->get($id);
				$dataSet = array(
					'name' => $owner->name,
					'slug'	=>url_title(strtolower(convert_accented_characters($owner->name))),
					'deleted' => 1
				);
				if($this->cip_owners_m->updateDelete($id, $dataSet))
				{
					$deleted++;
					$servers = $this->cip_servers_m->get_all();
					
					if($servers && count($servers)){
						foreach ($servers as $server){
							
							$config['hostname'] = $server->domain_name;
							$config['username'] = $server->database_user;
							$config['password'] = $server->database_password;
							$config['database'] = $server->database_name;
							$config['dbdriver'] = "mysql";
							$config['dbprefix'] = "";
							$config['pconnect'] = FALSE;
							$config['db_debug'] = FALSE;
							$config['cache_on'] = FALSE;
							$config['cachedir'] = "";
							$config['char_set'] = "utf8";
							$config['dbcollat'] = "utf8_general_ci";
							$config['port'] 	= 3306;
							
							$this->client_db = $this->load->database($config, TRUE);
							
							$this->client_db->where('id', $id);
							$this->client_db->update('default_cip_owners', $dataSet);
						    
						    $e = $this->client_db->_error_message();
						    $aff = $this->client_db->affected_rows();
							
							if($aff < 1) {
								$isSuccess = false;
								//echo "Error";
								//echo $e;
								
								$oldDataSet = array(
									'name' => $owner->name,
									'slug'	=>url_title(strtolower(convert_accented_characters($owner->name))),
									'deleted' => 0
								);
	
								$this->cip_owners_m->updateDelete($id, $oldDataSet);
							
								foreach ($servers as $server){
									$config['hostname'] = $server->domain_name;
									$config['username'] = $server->database_user;
									$config['password'] = $server->database_password;
									$config['database'] = $server->database_name;
									$config['dbdriver'] = "mysql";
									$config['dbprefix'] = "";
									$config['pconnect'] = FALSE;
									$config['db_debug'] = FALSE;
									$config['cache_on'] = FALSE;
									$config['cachedir'] = "";
									$config['char_set'] = "utf8";
									$config['dbcollat'] = "utf8_general_ci";
									$config['port'] 	= 3306;
									
									$this->client_db = $this->load->database($config, TRUE);
	
									$this->client_db->where('id', $id);
									$this->client_db->update('default_cip_owners', $oldDataSet); 
								}
								break;
							}
						}
					}
					
					
				}
				else
				{
					$isSuccess = false;
				}
				$to_delete++;
			}
			
			if(!$isSuccess){
				$this->session->set_flashdata('error', sprintf($this->lang->line('cirpho_owner_mass_delete_error'), $id));
			}else{
				$this->session->set_flashdata('success', sprintf($this->lang->line('cirpho_owner_mass_delete_success'), $deleted, $to_delete));
			}
		}		
		else
		{
			$this->session->set_flashdata('error', $this->lang->line('cirpho_owner_no_select_error'));
		}
		
		redirect('admin/cirpho/owners/index');
	}
	
	/**
	 * Callback method that checks the title of the category
	 * @access public
	 * @param string title The title to check
	 * @return bool
	 */
	public function _check_title($name = '')
	{
		if ($this->cip_owners_m->check_title($name))
		{
			$this->form_validation->set_message('_check_title', sprintf($this->lang->line('cirpho_owner_already_exist_error'), $name));
			return FALSE;
		}

		return TRUE;
	}
}